<?php

namespace Siese\LoginBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

use Siese\LoginBundle\Entity\Usuarios;
use Siese\EntityBundle\Entity\Funcionarios;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Siese\EntityBundle\Entity\UsuariosSedes;
use Siese\LoginBundle\Form\CambiarContrasenaType;
use Siese\LoginBundle\Form\RecuperarContrasenaType;

use Siese\LoginBundle\Form\CrearUsuariosType;
use Siese\LoginBundle\Form\EditarUsuariosType;
//use Siese\LoginBundle\Form\CambiarContrasenaType;
use Siese\LoginBundle\Form\LoginFormType;

class SecurityController extends Controller
{
    public function indexAction()
    {
        return $this->render('SieseLoginBundle:Default:index.html.twig');
    }
    
    public function logoutAction() 
    {
        
    }
    
    public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        $form = $this->createForm(new LoginFormType(), null);
        
        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(
                SecurityContext::AUTHENTICATION_ERROR
            );
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render('SieseLoginBundle:Security:login.html.twig',
            array(
                // last username entered by the user
                'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                'error'         => $error,
                'form'         => $form->createView()
            )
        );
    }
    
    public function indexUsuariosAction() {
      $em = $this->getDoctrine()->getManager();
      
      $entities = $em->getRepository('SieseLoginBundle:Usuarios')->findAll();
    
      return $this->render('SieseLoginBundle:Usuarios:index.html.twig',array('entities' => $entities));        
    }
    
    
    public function verUsuarioAction($id) {
      $em = $this->getDoctrine()->getManager();
      
      if(isset($id)):
        $entity = $em->getRepository('SieseLoginBundle:Usuarios')->find($id);    
      endif;
      
      return $this->render('SieseLoginBundle:Usuarios:ver.html.twig',array('entity' => $entity));    
    }
    
    public function crearUsuariosAction(Request $request) {
        
      $em = $this->getDoctrine()->getManager();
      
      $usuario = $this->getUser();
            
      //$funcionarioLogueado = $usuario->getFuncionario();
      //$dependencia = $funcionarioLogueado->getDependencia();
      
      $entity = new Usuarios();
      
      
      $form = $this->crearUsuariosForm($entity);
      $form->handleRequest($request);
        

      
      
      if($form->isValid()):
        
        $roles = $em->getRepository('SieseLoginBundle:Role')->find(1);
      
        $funcionario = new Funcionarios();
        $usuarioSedes = new UsuariosSedes();

        $funcionario->setCedula($form->get('cedula')->getData());
        $funcionario->setNombres($form->get('nombresFuncionario')->getData());
        $funcionario->setApellidos($form->get('apellidosFuncionario')->getData());
        $funcionario->setCorreoInstitucional($form->get('correoInstitucional')->getData());
        $funcionario->setCorreoPersonal($form->get('correoPersonal')->getData());
        $funcionario->setTelefono($form->get('telefono')->getData());
        
        $entity->addRole($roles);
        $entity->setFeIngreso(new \DateTime('now'));
        $entity->setSalt(md5(uniqid()));
        $entity->setIsActive(1);
        
        $encoder = $this->container->get('security.encoder_factory')->getEncoder($entity);
        $entity->setPassword($encoder->encodePassword($form->get('password')->getData(), $entity->getSalt()));      

        $em->persist($entity);
        $em->flush();
        
        $usuarioSedes->setSede($form->get('sede')->getData());
        $usuarioSedes->setUsuario($entity);
        
        $funcionario->setUsuario($entity);
        
        $em->persist($usuarioSedes);
        $em->persist($funcionario);
        $em->flush();
        
        return $this->redirect($this->generateUrl('crear-usuarios'));
      endif;

      
        return $this->render('SieseLoginBundle:Usuarios:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));      
    }

    
    
    public function editarUsuariosAction(Request $request,$id) {
        
      $em = $this->getDoctrine()->getManager();
      
      $usuario = $this->getUser();
            
      //$funcionarioLogueado = $usuario->getFuncionario();
      //$dependencia = $funcionarioLogueado->getDependencia();
      
      $entity = $em->getRepository('SieseLoginBundle:Usuarios')->find($id);
      
      
      $form = $this->editarUsuariosForm($entity);
      $form->handleRequest($request);
        

      
      
      if($form->isValid()):
        
        $funcionario = $entity->getFuncionario();
        

        $funcionario->setCedula($form->get('cedula')->getData());
        $funcionario->setNombres($form->get('nombresFuncionario')->getData());
        $funcionario->setApellidos($form->get('apellidosFuncionario')->getData());
        $funcionario->setCorreoInstitucional($form->get('correoInstitucional')->getData());
        $funcionario->setCorreoPersonal($form->get('correoPersonal')->getData());
        $funcionario->setTelefono($form->get('telefono')->getData());
        
        
        $entity->setSalt(md5(uniqid()));
       
        
        $encoder = $this->container->get('security.encoder_factory')->getEncoder($entity);
        $entity->setPassword($encoder->encodePassword($form->get('password')->getData(), $entity->getSalt()));      

        $em->persist($entity);
        $em->flush();
        
        
       foreach($entity->getSedesUsuario() as $row):
          $em->remove($row);
          $em->flush();
        endforeach;
        
        $usuarioSedes = new UsuariosSedes();
        $usuarioSedes->setSede($form->get('sede')->getData());
        $usuarioSedes->setUsuario($entity);
        
        $funcionario->setUsuario($entity);
        
        $em->persist($usuarioSedes);
        $em->persist($funcionario);
        $em->flush();
        
        return $this->redirect($this->generateUrl('index-usuarios'));
      endif;

      
        return $this->render('SieseLoginBundle:Usuarios:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));      
    }    

    private function crearUsuariosForm(Usuarios $entity,$idDependencia = null)
    {
        $form = $this->createForm(new CrearUsuariosType($idDependencia), $entity, array(
            'action' => $this->generateUrl('crear-usuarios'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Crear Usuario',
                                             'attr' => array('class' => 'btn btn-success',
                                                             'style' => 'margin-top:10px;')));

        return $form;
    }   
    
    private function editarUsuariosForm(Usuarios $entity,$idDependencia = null)
    {
        $form = $this->createForm(new EditarUsuariosType($idDependencia,$entity), $entity, array(
            'action' => $this->generateUrl('editar-usuario',array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Editar Usuario',
                                             'attr' => array('class' => 'btn btn-success',
                                                             'style' => 'margin-top:10px;')));

        return $form;
    }
    
    public function inactivarUsuariosAction(Request $request) {
      $em = $this->getDoctrine()->getManager();
      $idUsuario = $request->request->get('idUsuario');
      
      $usuario = $em->getRepository('SieseLoginBundle:Usuarios')->find($idUsuario);
      
      
      
      if($usuario):
        $estatusNuevo = ($usuario->getIsActive() == 1 ? 0 : 1);
      
        $usuario->setIsActive($estatusNuevo); 
        $em->persist($usuario);
        $em->flush();
      endif;
      
      return new Response('');         
    }
    
    public function cambiarContrasenaAction(Request $request)
    {
      $em = $this->getDoctrine()->getManager();
      $form = $this->cambiarContrasenaForm();
      $form->handleRequest($request);

      $user = $this->get('security.context')->getToken()->getUser();
      
      if ($form->isValid()) {
        $password = $form->get('password')->getData();
        
        $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
        $user->setPassword($encoder->encodePassword($password, $user->getSalt()));
        $em->persist($user);
        $em->flush();

        $this->get('session')->getFlashBag()->add(
            'notice',
            'La contraseña ha sido cambiada exitosamente.'
        );
        
        return $this->redirect($this->generateUrl('inicio'));
      }
      
      return $this->render('SieseLoginBundle:Security:cambiar_contrasena.html.twig', array(
          'form' => $form->createView()
      ));
    }    

    protected function cambiarContrasenaForm() {
        $form = $this->createForm(new CambiarContrasenaType(),null, array(
            'action' => $this->generateUrl('cambiar-contrasena'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Cambiar Contraseña',
                                             'attr' => array('class' =>'btn btn-success')));

        return $form;        
    }
    
    
       public function recuperarContrasenaAction(Request $request)
    {
      $em = $this->getDoctrine()->getManager();
      $form = $this->recuperarContrasenaForm();
      $form->handleRequest($request);

      //$user = $this->get('security.context')->getToken()->getUser();
      
      if ($form->isValid()) {
        $password = $form->get('password')->getData();
        
        $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
        $user->setPassword($encoder->encodePassword($password, $user->getSalt()));
        $em->persist($user);
        $em->flush();

        $this->get('session')->getFlashBag()->add(
            'notice',
            'La contraseña ha sido cambiada exitosamente.'
        );
        
        //return $this->redirect($this->generateUrl('inicio'));
        
      }
      
     
    }    
    
    public  function recuperarContrasenaForm() {
           $form = $this->createForm( new RecuperarContrasenaType(),null, array(
                     'action' => $this->generateUrl('recuperar-contrasena'),
                    'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Recuperar Contraseña',
                                             'attr' => array('class' =>'btn btn-success')));

        return $form;        
    }
    
}
